/*
 *    Thing Game Library
 *   Copyright (C)2005 - 2010 Eduardo Nunes Pereira (eduardonunesp at gmail dot com)
 *
 *   This program/library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 *   This program/library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 *    You should have received a copy of the GNU Lesser General Public
 * License along with this program/library ; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef __THREAD_HPP__
#define __THREAD_HPP__

#include <SDL/SDL_thread.h>

struct ThreadCommon
{
    struct ThreadDataCommon
    {
        ThreadDataCommon() {}
        virtual ~ThreadDataCommon() {}
        virtual int run() = 0;

        ThreadCommon *_thread;
    };

    ThreadCommon() {}
};

struct Thread : ThreadCommon
{
    template <typename T, typename A>
    struct ThreadData : ThreadDataCommon
    {
        ThreadData(T data, A arg) : _data(data), _arg(arg) {}
        virtual ~ThreadData() {}

        int run()
        {
            _data(_arg);
            return 0;
        }
        
        T _data;
        A _arg;
    };
   
    template <typename T, typename A>
    Thread(T obj, A arg) : _thread_info(new ThreadData<T,A>(obj, arg))
    {
        _thread_info->_thread = this;
    }

    bool start()
    {
        _thread = SDL_CreateThread(run, _thread_info);
        
        if(_thread) return false;
        else        return true;
    }

    bool kill()
    {
        if(_thread) return false;
        SDL_KillThread(_thread);
        _thread = NULL;
        return true;
    }
   
private:
    void exit(int status)
    {
        if(_thread) return;
        SDL_KillThread(_thread);
        _thread = NULL;
    }

protected:
    static int run(void *obj)
    {
        ThreadDataCommon * data = (ThreadDataCommon*) obj;
        int ret = data->run();
        
        ((Thread*)(data->_thread))->exit(ret);
        return 0;
    }

    ThreadDataCommon *_thread_info;
    SDL_Thread *_thread;
};

#endif /* __THREAD_HPP__ */
